package com.tools.javacompiler;

import org.junit.Test;

import javax.tools.*;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

public class JavaCompilerExample {
    public static void main(String[] args) throws IOException {
        File[] files1 = {new File("I:\\jbProject\\javastudy\\src\\com\\util\\DateDemo.java"),
                new File("I:\\jbProject\\javastudy\\src\\com\\util\\HashMapDemo.java"),
                new File("I:\\jbProject\\javastudy\\src\\com\\ylw\\tools\\attach\\VirtualMachineDemo.java")};
//        File[] files2 = {new File("")};
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits1 =
                fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1));
        Iterable<String> options = Arrays.asList("-d","I:\\jbProject\\javastudy\\out\\production\\javastudy");


        compiler.getTask(null, fileManager, null, options, null, compilationUnits1).call();
//        Iterable<? extends JavaFileObject> compilationUnits2 =
//                fileManager.getJavaFileObjects(files2); // use alternative method
//        // reuse the same file manager to allow caching of jar filesLombokProcessor
//        compiler.getTask(null, fileManager, null, null, null, compilationUnits2).call();

        fileManager.close();
    }

    /**
     * 设置监听器 用来输出编译时的异常信息
     * @throws IOException
     */
    @Test
    public void testDiagnosticCollector() throws IOException {
        Iterable<? extends JavaFileObject> compilationUnits= null;
//        compilationUnits = new SimpleJavaFileObject();
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
        compiler.getTask(null, fileManager, diagnostics, null, null, compilationUnits).call();

        for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics())
            System.out.format("Error on line %d in %s%n",
                    diagnostic.getLineNumber(),
                    diagnostic.getSource().toUri());

        fileManager.close();
    }
}
